﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VOL.Core.Utilities
{
  
        #region 条件
        // 基础条件接口
        public interface ICondition
        {
            bool Evaluate();
            string Expression { get; }
        }

        // 基本运算符枚举
        public enum ConditionOperator
        {
        /// <summary>
        /// ==等于
        /// </summary>
            Equal,
        /// <summary>
        /// !=
        /// </summary>
        NotEqual,
        /// <summary>
        /// >
        /// </summary>
        GreaterThan,
        /// <summary>
        /// <
        /// </summary>
        LessThan,
        /// <summary>
        /// >=
        /// </summary>
        GreaterOrEqual,
        /// <summary>
        /// <=
        /// </summary>
        LessOrEqual,
        /// <summary>
        /// 包含
        /// </summary>

        Contains,
        /// <summary>
        /// 开头为
        /// </summary>
        StartsWith,
        /// <summary>
        /// 结尾为
        /// </summary>
        EndsWith
    }

        // 基础比较条件抽象类
        public abstract class BaseCondition : ICondition
        {
            protected string FieldName { get; }
            protected ConditionOperator Operator { get; }

            public abstract bool Evaluate();
            public abstract string Expression { get; }

            protected string OperatorSymbol
            {
                get
                {
                    return Operator switch
                    {
                        ConditionOperator.Equal => "==",
                        ConditionOperator.NotEqual => "!=",
                        ConditionOperator.GreaterThan => ">",
                        ConditionOperator.LessThan => "<",
                        ConditionOperator.GreaterOrEqual => ">=",
                        ConditionOperator.LessOrEqual => "<=",
                        ConditionOperator.Contains => "包含",
                        ConditionOperator.StartsWith => "开头为",
                        ConditionOperator.EndsWith => "结尾为",
                        _ => "?"
                    };
                }
            }

            protected BaseCondition(string fieldName, ConditionOperator op)
            {
                FieldName = fieldName;
                Operator = op;
            }
        }

        // 工序条件实现
        public class ProcessCondition : BaseCondition
        {
            public string CurrentProcess { get; }
            public HashSet<string> Processes { get; }

            public override string Expression =>
                $"{FieldName} {OperatorSymbol} [{string.Join(",", Processes)}]";

            public ProcessCondition(string fieldName, string currentProcess,
                IEnumerable<string> processes, ConditionOperator op = ConditionOperator.Contains)
                : base(fieldName, op)
            {
                CurrentProcess = currentProcess;
                Processes = new HashSet<string>(processes, StringComparer.OrdinalIgnoreCase);
            }

            public override bool Evaluate()
            {
                return Operator switch
                {
                    ConditionOperator.Contains => Processes.Contains(CurrentProcess),
                    ConditionOperator.Equal => Processes.Contains(CurrentProcess),
                    ConditionOperator.NotEqual => !Processes.Contains(CurrentProcess),
                    ConditionOperator.StartsWith => Processes.Any(p => CurrentProcess.StartsWith(p, StringComparison.OrdinalIgnoreCase)),
                    ConditionOperator.EndsWith => Processes.Any(p => CurrentProcess.EndsWith(p, StringComparison.OrdinalIgnoreCase)),
                    _ => false
                };
            }
        }

        // 数值条件实现
        public class NumericCondition : BaseCondition
        {
            public double Value { get; }
            public double CompareValue { get; }

            public override string Expression =>
                $"{FieldName} {OperatorSymbol} {CompareValue} (当前值:{Value})";

            public NumericCondition(string fieldName, double value,
                ConditionOperator op, double compareValue)
                : base(fieldName, op)
            {
                Value = value;
                CompareValue = compareValue;
            }

            public override bool Evaluate()
            {
                return Operator switch
                {
                    ConditionOperator.Equal => Math.Abs(Value - CompareValue) < 0.0001,
                    ConditionOperator.NotEqual => Math.Abs(Value - CompareValue) > 0.0001,
                    ConditionOperator.GreaterThan => Value > CompareValue,
                    ConditionOperator.LessThan => Value < CompareValue,
                    ConditionOperator.GreaterOrEqual => Value >= CompareValue,
                    ConditionOperator.LessOrEqual => Value <= CompareValue,
                    _ => false
                };
            }
        }

        // 布尔条件实现
        public class BooleanCondition : BaseCondition
        {
            public bool Value { get; }

            public override string Expression =>
                $"{FieldName} {OperatorSymbol} {Value}";

            public BooleanCondition(string fieldName, ConditionOperator op, bool value)
                : base(fieldName, op)
            {
                Value = value;
            }

            public override bool Evaluate()
            {
                return Operator switch
                {
                    ConditionOperator.Equal => Value,
                    ConditionOperator.NotEqual => !Value,
                    _ => false
                };
            }
        }

        // 文本条件实现
        public class TextCondition : BaseCondition
        {
            public string Value { get; }
            public string CompareValue { get; }

            public override string Expression =>
                $"{FieldName} {OperatorSymbol} '{CompareValue}' (当前值:'{Value}')";

            public TextCondition(string fieldName, string value,
                ConditionOperator op, string compareValue)
                : base(fieldName, op)
            {
                Value = value;
                CompareValue = compareValue;
            }

            public override bool Evaluate()
            {
                return Operator switch
                {
                    ConditionOperator.Equal => string.Equals(Value, CompareValue, StringComparison.OrdinalIgnoreCase),
                    ConditionOperator.NotEqual => !string.Equals(Value, CompareValue, StringComparison.OrdinalIgnoreCase),
                    ConditionOperator.Contains => Value?.Contains(CompareValue, StringComparison.OrdinalIgnoreCase) ?? false,
                    ConditionOperator.StartsWith => Value?.StartsWith(CompareValue, StringComparison.OrdinalIgnoreCase) ?? false,
                    ConditionOperator.EndsWith => Value?.EndsWith(CompareValue, StringComparison.OrdinalIgnoreCase) ?? false,
                    _ => false
                };
            }
        }

        // 逻辑组合器基类
        public abstract class LogicCondition : ICondition
        {
            protected List<ICondition> Conditions { get; } = new();
            protected string LogicSymbol { get; }

            public abstract bool Evaluate();
            public abstract string Expression { get; }

            protected LogicCondition(string symbol)
            {
                LogicSymbol = symbol;
            }

            public LogicCondition AddCondition(ICondition condition)
            {
                Conditions.Add(condition);
                return this;
            }

            public LogicCondition AddConditions(params ICondition[] conditions)
            {
                Conditions.AddRange(conditions);
                return this;
            }
        }

        // AND 条件组合器
        public class AndCondition : LogicCondition
        {
            public AndCondition() : base("AND") { }

            public override bool Evaluate() =>
                Conditions.Count > 0 && Conditions.All(c => c.Evaluate());

            public override string Expression =>
                $"({string.Join($" {LogicSymbol} ", Conditions.Select(c => c.Expression))})";
        }

        // OR 条件组合器
        public class OrCondition : LogicCondition
        {
            public OrCondition() : base("OR") { }

            public override bool Evaluate() =>
                Conditions.Count == 0 || Conditions.Any(c => c.Evaluate());

            public override string Expression =>
                $"({string.Join($" {LogicSymbol} ", Conditions.Select(c => c.Expression))})";
        }

        // NOT 条件组合器
        public class NotCondition : ICondition
        {
            private readonly ICondition _condition;

            public string Expression => $"NOT ({_condition.Expression})";

            public NotCondition(ICondition condition)
            {
                _condition = condition;
            }

            public bool Evaluate() => !_condition.Evaluate();
        }

        // 表达式构建器
        public class ConditionBuilder
        {
            private ICondition _rootCondition;

            public ConditionBuilder SetRoot(ICondition root)
            {
                _rootCondition = root;
                return this;
            }

            public bool Evaluate() => _rootCondition?.Evaluate() ?? false;

            public string GetExpressionTree()
            {
                if (_rootCondition == null)
                    return "未配置条件";

                return _rootCondition.Expression;
            }

            public string VisualizeExpressionTree()
            {
                var rs = "表达式树可视化:" + Environment.NewLine;
                //   Console.WriteLine("表达式树可视化:");
                // Console.WriteLine(GetExpressionTree());
                rs += GetExpressionTree() + Environment.NewLine;
                rs += $"\n计算结果: {Evaluate()}";

                return rs;
            }
        }

        // 时间范围条件实现
        public class TimeRangeCondition : BaseCondition
        {
            public DateTime CurrentTime { get; }
            public TimeSpan StartTime { get; }
            public TimeSpan EndTime { get; }

            public override string Expression =>
                $"{FieldName} {OperatorSymbol} {StartTime}-{EndTime} (当前:{CurrentTime.TimeOfDay})";

            public TimeRangeCondition(string fieldName, DateTime currentTime,
                TimeSpan startTime, TimeSpan endTime)
                : base(fieldName, ConditionOperator.Equal)
            {
                CurrentTime = currentTime;
                StartTime = startTime;
                EndTime = endTime;
            }

            public override bool Evaluate()
            {
                var current = CurrentTime.TimeOfDay;
                return current >= StartTime && current <= EndTime;
            }
        }


        // 复合条件（支持动态条件组合）
        public class CompositeCondition : ICondition
        {
            private readonly Func<bool> _evaluator;
            private readonly string _description;

            public string Expression => _description;

            public CompositeCondition(Func<bool> evaluator, string description)
            {
                _evaluator = evaluator;
                _description = $"复合条件({description})";
            }

            public bool Evaluate() => _evaluator();

            // 示例工厂方法
            public static CompositeCondition CreateShiftCondition(
                string shiftName, DateTime checkTime)
            {
                var shifts = new Dictionary<string, (TimeSpan Start, TimeSpan End)>()
                {
                    ["早班"] = (new TimeSpan(6, 0, 0), new TimeSpan(14, 0, 0)),
                    ["中班"] = (new TimeSpan(14, 0, 0), new TimeSpan(22, 0, 0)),
                    ["晚班"] = (new TimeSpan(22, 0, 0), new TimeSpan(6, 0, 0))
                };

                return new CompositeCondition(
                    () => shifts[shiftName].Start <= checkTime.TimeOfDay
                          && checkTime.TimeOfDay <= shifts[shiftName].End,
                    $"班次[{shiftName}]时间验证"
                );
            }
        }




        #endregion
    
}
